//
//  Test.m
//  SKarPro
//
//  Created by macbook on 2/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "KarFavourites.h"
//#import "ViewLyricViewController.h"
//#import "SoncaIDLoginViewController.h"
//#import "KaraokeViewController.h"
//#import "KaraokeNotification.h"
#import "DisplayCellView.h"
#import "DBInterface.h"
//#import "Playlists.h"
//#import "MySong.h"
#import "Song.h"

@interface KarFavourites ()

@end

@implementation KarFavourites
//@synthesize optionAlert;

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 22;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSInteger songcount = [[self DataForTableView:tableView] count];
    CGRect frame = [self.view bounds];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(8.5, 0, frame.size.width, 21.0)];
    [view setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin];
    [view setBackgroundColor:KOK_COLOR_WHITE];
    
    UILabel *labelTitle = [[UILabel alloc] initWithFrame:view.frame];
    [labelTitle setText:[NSString stringWithFormat:@"%d bài hát", songcount]];
    [labelTitle setTextColor:KOK_COLOR_LIGHT_BROWN];
    
    [view addSubview:labelTitle];
    
    return view;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self DataForTableView:tableView] count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self tableView:tableView cellForRowAtIndexPath:indexPath isExpanded:NO];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded:(BOOL)isExpanded
{
    static NSString *CellIdentifier = @"DisplayCell";
    
    DisplayCellView *cell = (DisplayCellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DisplayCellViewIPad" owner:self options:nil] objectAtIndex:0];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DisplayCellView" owner:self options:nil] objectAtIndex:0];
        }
    }
    
    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
    [cell setDelegate:self];
    [cell setIndexPath:indexPath];
    [cell setTableView:tableView];
    [cell configureCellForSongObject:song atIndexPath:indexPath withSearchString:@"" andShowFree:[song purchased] inPlaylist:false];
    
    if (!isExpanded) //prepare the cell as if it was collapsed! (without any animation!)
	{
		cell.btnMenu.transform = CGAffineTransformMakeRotation(0);
	}
	else ///prepare the cell as if it was expanded! (without any animation!)
	{
		cell.btnMenu.transform = CGAffineTransformMakeRotation(3.14);
	}
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self tableView:tableView heightForRowAtIndexPath:indexPath isExpanded:NO];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded:(BOOL)isexpanded
{
	if (isexpanded)
		return 99;
	return 55;
}

- (void) tableView:(UITableView *)tableView expandCell:(UITableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    [UIView animateWithDuration:.5 animations:^{
        DisplayCellView *dCell = (DisplayCellView *) cell;
        [dCell.btnMenu setTransform:CGAffineTransformMakeRotation(3.14)];
	}];
}

-(void) tableView:(UITableView *)tableView collapseCell:(UITableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    DisplayCellView *dCell = (DisplayCellView *) cell;
    [dCell.btnMenu setTransform:CGAffineTransformMakeRotation(0)];
}

- (void) tableView:(UITableView *) tableView didSelectOnMenuItemAtIndexPath:(NSIndexPath *)indexPath
{
//    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
//    if (!optionAlert) {
//        optionAlert = [[ContextPopup alloc] initWithContextType:ContextTypeFavourite parentView:self andDetail:song];
//    }
//    [optionAlert initPopupContextTypeFavourite:song]; 
//    [optionAlert show];
}

- (void) tableView:(UITableView *) tableView didSelectOnFunctionAtIndexPath:(NSIndexPath *)indexPath
{
//    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
//    if ([song purchased]) {
//        if([Playlists containSong:song])
//        {
//            [Playlists removeSong:song];
//        }else {
//            [Playlists addSongToPlaylist:song];
//        }
//    }else {
//        SoncaIDLoginViewController *loginView = [[SoncaIDLoginViewController alloc] initWithNibName:@"SoncaIDLoginViewController" bundle:nil];
//        [self.navigationController pushViewController:loginView animated:YES];
//    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
//    if ([song purchased]) {
//        KaraokeViewController *kokPlayer = nil;
//        if(IS_IPAD) {
//            kokPlayer = [[KaraokeViewController alloc] initWithNibName:@"KaraokeViewController-ipad" bundle:nil];
//        }else {
//            kokPlayer = [[KaraokeViewController alloc] initWithNibName:@"KaraokeViewController" bundle:nil];
//        }
//        
//        [Playlists firstReserveSong:song];
//        [self.navigationController pushViewController:kokPlayer animated:YES];
//    }else {
//        SoncaIDLoginViewController *loginView = [[SoncaIDLoginViewController alloc] initWithNibName:@"SoncaIDLoginViewController" bundle:nil];
//        [self.navigationController pushViewController:loginView animated:YES];
//    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - UIViewHandler
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setSearchBarButtonItemHidden:YES];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    appDelegate = [[UIApplication sharedApplication] delegate];
    
//    [KaraokeNotification registerKaraoke:self notification:KaraokePlaylistChanged selector:@selector(playlistChangedNotificationHandler:)];
//    [KaraokeNotification registerKaraoke:self notification:KaraokeFavouriteChanged selector:@selector(favouriteChangedNotificationHandler:)];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableViewData setHidden:YES];
    [self.loadingIndicator startAnimating];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(allData) {
        [self.tableViewData reloadData];
        [self.loadingIndicator stopAnimating];
        [self.tableViewData setHidden:NO];
    }
}

#pragma mark - setEditing
- (void) toggleEditing
{
    if (isEditing) {
        isEditing = false;
    }else {
        isEditing = true;
    }
    [self setEditing:isEditing animated:YES];
}

- (void) setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableViewData setEditing:editing animated:animated];
    if (editing) {
        UIBarButtonItem *editItem = [self.navigationItem.rightBarButtonItems objectAtIndex:0];
        [(UIButton *)(editItem.customView) setImage:[UIImage imageNamed:@"done.png"]forState:UIControlStateNormal];
        UIBarButtonItem *settingItem = [self.navigationItem.rightBarButtonItems objectAtIndex:1];
        [settingItem.customView setHidden:YES];
        
        [self.navigationItem.leftBarButtonItem.customView setHidden:YES]; 
    }else {
        UIBarButtonItem *editItem = [self.navigationItem.rightBarButtonItems objectAtIndex:0];
        [(UIButton *)(editItem.customView) setImage:[UIImage imageNamed:@"edit.png"]forState:UIControlStateNormal];
        UIBarButtonItem *settingItem = [self.navigationItem.rightBarButtonItems objectAtIndex:1];
        [settingItem.customView setHidden:NO];
        
        [self.navigationItem.leftBarButtonItem.customView setHidden:NO];
    }
}

- (void) dealloc
{
//    [KaraokeNotification unregisterKaraoke:self notification:KaraokePlaylistChanged];
//    [KaraokeNotification unregisterKaraoke:self notification:KaraokeFavouriteChanged];
}

#pragma mark - reloadData
- (void) reloadDisplayData
{
    if(allData == nil)
    {
        allData = [NSMutableArray arrayWithArray:[[DBInterface instance] queryFavouriteSong:@""]];
        [tableViewData reloadData];
        [self.loadingIndicator stopAnimating];
        [tableViewData setHidden:NO];
        if ([allData count] > 0) {
            [self.tableViewData scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }
}

#pragma mark - songPlaylistHandler
- (void) playlistChangedNotificationHandler:(NSNotification *) notification
{
    [tableViewData reloadData];
    [self updateKaraokeBarButton];
}

- (void) favouriteChangedNotificationHandler:(NSNotification *) notification
{
    allData = [NSMutableArray arrayWithArray:[[DBInterface instance] queryFavouriteSong:@""]];
    [tableViewData reloadData];
    [self.loadingIndicator stopAnimating];
    [tableViewData setHidden:NO];
    if ([allData count] > 0) {
        [self.tableViewData scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

@end
